﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using Newtonsoft.Json;
using System.Windows.Resources;
using System.IO.IsolatedStorage;
using System.IO;

namespace StravaUploader
{
    public class StravaCommunicator
    {
        static private WebClient requestSender = new WebClient();
        static private String authJSON;
        static public String token;

        static private String SERVER_URL = "http://www.strava.com";
        //static private const String SERVER_URL = "http://172.24.224.50";

        static private String SERVER_LOGIN_PATH_URL = "/api/v2/authentication/login";
        //static private const String SERVER_LOGIN_PATH_URL = "tmp/strava.json";

        static private String SERVER_UPLOAD_PATH_URL = "/api/v2/upload";
        //static private const String SERVER_LOGIN_PATH_URL = "/api/v2/upload";


        static public void Auth(String email, String password)
        {
            requestSender.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var uri = new Uri(SERVER_URL + SERVER_LOGIN_PATH_URL, UriKind.Absolute);
            StringBuilder postData = new StringBuilder();
            postData.AppendFormat("{0}={1}", "email", HttpUtility.UrlEncode(email));
            postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(password));

            requestSender.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
            requestSender.UploadStringCompleted += new UploadStringCompletedEventHandler(requestSender_UploadStringCompleted);
            requestSender.UploadStringAsync(uri, "POST", postData.ToString());

            StateHolder.LoginDone = true;

        }

        static void requestSender_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                authJSON = e.Result;
                System.Diagnostics.Debug.WriteLine("Auth results: " + authJSON);
                StravaAuth auth = JsonConvert.DeserializeObject<StravaAuth>(authJSON);
                StateHolder.LoginDone = true;
                token = auth.token;
            }
            else
            {
                MessageBox.Show("Auth failed.");
                System.Diagnostics.Debug.WriteLine("Auth failed: " + e.Error);
                StateHolder.LoginDone = false;
            }
        }


        internal static void AddAuthCompletedHandler(UploadStringCompletedEventHandler uploadStringCompletedEventHandler)
        {
            requestSender.UploadStringCompleted += new UploadStringCompletedEventHandler(uploadStringCompletedEventHandler);
        }

        static public void UploadTrack()
        {
            SaveTrack();

            requestSender.Headers[HttpRequestHeader.ContentType] = "multipart/form-data";
            var uri = new Uri(SERVER_URL + SERVER_UPLOAD_PATH_URL, UriKind.Absolute);
            StringBuilder postData = new StringBuilder();
            postData.AppendFormat("{0}={1}", "token", HttpUtility.UrlEncode(token));
            postData.AppendFormat("&{0}={1}", "data", HttpUtility.UrlEncode(GPSHelper.getGPXString()));
            postData.AppendFormat("&{0}={1}", "type", HttpUtility.UrlEncode("gpx"));

            requestSender.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
            requestSender.UploadStringCompleted += new UploadStringCompletedEventHandler(TrackCompleted);
            requestSender.UploadStringAsync(uri, "POST", postData.ToString());
            StateHolder.Finished = true;
            StateHolder.Started = false;
        }

        static public void SaveTrack()
        {
            System.Diagnostics.Debug.WriteLine(GPSHelper.getGPXString());
            /*MessageBox.Show(GPSHelper.getGPXString());
            
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri("gpx-for-strava.gpx", UriKind.Relative));

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string directoryName = System.IO.Path.GetDirectoryName("gpx-for-strava.gpx");
                if (!string.IsNullOrEmpty(directoryName) && !myIsolatedStorage.DirectoryExists(directoryName))
                {
                    myIsolatedStorage.CreateDirectory(directoryName);
                }

                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("gpx-for-strava.gpx", FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        writer.WriteLine(GPSHelper.getGPXString());
                    }
                }
            }*/
        }


        static void TrackCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String res = e.Result;
                System.Diagnostics.Debug.WriteLine("Upload results: " + res);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Upload failed: " + e.Error);
                MessageBox.Show(e.Error.Message);
            }
            StateHolder.Finished = true;
        }
    }
}
